<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { type FormRules } from 'element-plus'

interface Props {
  status: string
  data?: Record<string, any> | never | null
}

const props = withDefaults(defineProps<Props>(), {
  status: 'add',
  data: null,
})

const formRef = ref()

const form = reactive<Record<string, any>>({})

const rules = ref<FormRules>({
  cover: [{ required: true, message: '封面不能为空!', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空!', trigger: 'blur' }],
  category1Id: [{ required: true, message: '分类1不能为空!', trigger: 'blur' }],
  category2Id: [{ required: true, message: '分类2不能为空!', trigger: 'blur' }],
  description: [{ required: true, message: '描述不能为空!', trigger: 'blur' }],
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      form[key] = props.data![key]
    })
  }
}

const submitForm = () => {
  return new Promise((resolve: any) => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        resolve(form)
      }
    })
  })
}

defineExpose({
  submitForm,
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="封面:" prop="cover">
        <el-input v-model="form.cover" placeholder="请输入封面" style="width: 214px"> </el-input>
      </el-form-item>
      <el-form-item label="名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" style="width: 214px"> </el-input>
      </el-form-item>
      <el-form-item label="分类一:" prop="category1Id">
        <el-input v-model="form.category1Id" placeholder="请输入分类" style="width: 214px">
        </el-input>
      </el-form-item>
      <el-form-item label="分类二:" prop="category2Id">
        <el-input v-model="form.category2Id" placeholder="请输入分类" style="width: 214px">
        </el-input>
      </el-form-item>
      <el-form-item label="描述:" prop="description">
        <el-input v-model="form.description" placeholder="请输入描述" style="width: 214px">
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
